/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * Ingreso.java
 *
 * Created on 10-dic-2013, 8:45:50
 */
package sistemataller;

import core.*;
import java.sql.*;
import java.awt.*;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author Oscar Aguilera
 */
public class Ingreso extends javax.swing.JInternalFrame {

    int fila = -1;
    private String condiciones, tbls;
    private Object[][] result;
    private Query cmd;
    private Conexion conn;
    String tablamaster = "tbl_fichaAuto";
    String[] campos = {"id_fichaAuto", "patente", "rut_cliente", "id_usuario", "comentarios"};
    String[] titcols = {"id", "patente", "rut_cliente", "nombres", "apellidos", "comentarios"};
    String nomkey = "id_fichaAuto";
    DefaultTableModel datos;
    String idmarca = null;
    String idmodelo = null;
    String idUsuario = null;

    public Ingreso(String idUsuario) {
        this.idUsuario = idUsuario;
        initComponents();
        combomarcas();
        cmbModelo.removeAllItems();
        limpiar();
    }

   private void   grabaformulario(){
       
        String id = txtId.getText();
        String patente = txtPatente.getText();
        String rut = txtRut.getText();
        String nombres = txtNombres.getText();
        String apellidos = txtApellidos.getText();
        String fono = txtFono.getText();
        String comentarios = txtComentarios.getText();


        EntradaCombo item1 = (EntradaCombo) cmbMarca.getSelectedItem();
        EntradaCombo item2 = (EntradaCombo) cmbModelo.getSelectedItem();

        try {
            idmarca = item1.getValue();
        } catch (Exception e) {
            System.out.println("error combo marca: " + cmbMarca.getSelectedItem());
        }

        try {
            idmodelo = item2.getValue();
        } catch (Exception e) {
            System.out.println("error combo modelo: " + cmbModelo.getSelectedItem());
        }

       conn = new Conexion();
        cmd = new Query(conn);
        String[] columna = {"patente"};
        condiciones = "patente='" + patente + "'";
        if (!cmd.existeCampo(columna, condiciones, "tbl_auto")) {


            String values = "'" + patente + "','" + idmodelo + "','" + rut + "','0'";
            String campos1 = cmd.getNomCols(conn.bd, "tbl_auto");
            cmd.insertRegistro("tbl_auto", campos1, values);

        }

        String[] columna2 = {"rut_cliente"};
        condiciones = "rut_cliente='" + rut + "'";
        if (!cmd.existeCampo(columna2, condiciones, "tbl_cliente")) {


            String values = "'" + rut + "','" + nombres + "','" + apellidos + "','" + fono + "'";
            String campos2 = cmd.getNomCols(conn.bd, "tbl_cliente");
            cmd.insertRegistro("tbl_cliente", campos2, values);

        }




        if (id.equals("")) {

            String valor = "'0','" + patente + "','" + rut + "','" + idUsuario + "','" + comentarios + "'";
            String campo = cmd.getNomCols(conn.bd, tablamaster);
            cmd.insertRegistro(tablamaster, campo, valor);




        } else {

            // actualiza datos
            String values;
            values = "patente='" + patente + "',"
                    + "rut_cliente='" + rut + "',"
                    + "id_usuario='" + idUsuario + "',"
                    + "comentarios='" + comentarios + "'";
            cmd.actualizaRegistro(tablamaster, values, nomkey + "=" + id);

        }
        conn.desconectar();

        limpiar();
    }
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel3 = new javax.swing.JPanel();
        jLabel3 = new javax.swing.JLabel();
        cmbMarca = new javax.swing.JComboBox();
        jLabel1 = new javax.swing.JLabel();
        txtRut = new javax.swing.JTextField();
        btnRut = new javax.swing.JButton();
        jLabel6 = new javax.swing.JLabel();
        txtNombres = new javax.swing.JTextField();
        jLabel8 = new javax.swing.JLabel();
        txtApellidos = new javax.swing.JTextField();
        jLabel9 = new javax.swing.JLabel();
        txtFono = new javax.swing.JTextField();
        jLabel4 = new javax.swing.JLabel();
        cmbModelo = new javax.swing.JComboBox();
        btnPatente = new javax.swing.JButton();
        txtPatente = new javax.swing.JTextField();
        jLabel5 = new javax.swing.JLabel();
        jSeparator1 = new javax.swing.JSeparator();
        txtId = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        lblEstado = new javax.swing.JLabel();
        jPanel5 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        tblRegistros = new javax.swing.JTable();
        jPanel4 = new javax.swing.JPanel();
        btnGrabar = new javax.swing.JButton();
        btnBorrar = new javax.swing.JButton();
        btnSalir = new javax.swing.JButton();
        btnNuevo = new javax.swing.JButton();
        jScrollPane2 = new javax.swing.JScrollPane();
        txtComentarios = new javax.swing.JTextArea();
        jLabel10 = new javax.swing.JLabel();
        jSeparator2 = new javax.swing.JSeparator();

        setClosable(true);
        setIconifiable(true);
        setResizable(true);
        setTitle("Orden de trabajo");

        jLabel3.setText("Marca");

        cmbMarca.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
        cmbMarca.addItemListener(new java.awt.event.ItemListener() {
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                cmbMarcaItemStateChanged(evt);
            }
        });
        cmbMarca.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cmbMarcaActionPerformed(evt);
            }
        });

        jLabel1.setText("Rut ");

        txtRut.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                txtRutActionPerformed(evt);
            }
        });
        txtRut.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusLost(java.awt.event.FocusEvent evt) {
                txtRutFocusLost(evt);
            }
        });

        btnRut.setText("Consultar");
        btnRut.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnRutActionPerformed(evt);
            }
        });

        jLabel6.setText("Nombre");

        jLabel8.setText("Apellidos");

        jLabel9.setText("Telefono");

        jLabel4.setText("Modelo");

        cmbModelo.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
        cmbModelo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cmbModeloActionPerformed(evt);
            }
        });

        btnPatente.setText("Consultar");
        btnPatente.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnPatenteActionPerformed(evt);
            }
        });
        btnPatente.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                btnPatenteKeyPressed(evt);
            }
        });

        txtPatente.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusLost(java.awt.event.FocusEvent evt) {
                txtPatenteFocusLost(evt);
            }
        });

        jLabel5.setText("Patente");

        txtId.setBackground(new java.awt.Color(217, 217, 217));
        txtId.setEditable(false);
        txtId.setForeground(new java.awt.Color(0, 8, 255));
        txtId.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                txtIdActionPerformed(evt);
            }
        });

        jLabel2.setText("Nº Ingreso");

        lblEstado.setForeground(new java.awt.Color(0, 0, 153));

        org.jdesktop.layout.GroupLayout jPanel3Layout = new org.jdesktop.layout.GroupLayout(jPanel3);
        jPanel3.setLayout(jPanel3Layout);
        jPanel3Layout.setHorizontalGroup(
            jPanel3Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jPanel3Layout.createSequentialGroup()
                .add(jPanel3Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(jPanel3Layout.createSequentialGroup()
                        .add(30, 30, 30)
                        .add(jPanel3Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                            .add(jPanel3Layout.createSequentialGroup()
                                .add(jPanel3Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                                    .add(jLabel1)
                                    .add(jLabel6)
                                    .add(jLabel8)
                                    .add(jLabel9))
                                .add(18, 18, 18)
                                .add(jPanel3Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                                    .add(jPanel3Layout.createSequentialGroup()
                                        .add(txtRut, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 106, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                                        .add(22, 22, 22)
                                        .add(btnRut, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 93, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                                    .add(txtFono, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 220, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                                    .add(txtApellidos, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 615, Short.MAX_VALUE)
                                    .add(txtNombres, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 615, Short.MAX_VALUE)))
                            .add(jPanel3Layout.createSequentialGroup()
                                .add(jPanel3Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING, false)
                                    .add(org.jdesktop.layout.GroupLayout.LEADING, jPanel3Layout.createSequentialGroup()
                                        .add(jPanel3Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                                            .add(jLabel3)
                                            .add(jLabel4))
                                        .add(29, 29, 29)
                                        .add(jPanel3Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                                            .add(cmbModelo, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                                            .add(cmbMarca, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                        .add(lblEstado, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 253, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                                    .add(org.jdesktop.layout.GroupLayout.LEADING, jPanel3Layout.createSequentialGroup()
                                        .add(jLabel5)
                                        .add(30, 30, 30)
                                        .add(txtPatente, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 107, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                                        .add(btnPatente, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 89, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                                        .add(18, 18, 18)
                                        .add(jLabel2)
                                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                                        .add(txtId, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 78, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)))
                                .add(238, 238, 238))))
                    .add(jPanel3Layout.createSequentialGroup()
                        .addContainerGap()
                        .add(jSeparator1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 702, Short.MAX_VALUE)))
                .addContainerGap())
        );
        jPanel3Layout.setVerticalGroup(
            jPanel3Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(org.jdesktop.layout.GroupLayout.TRAILING, jPanel3Layout.createSequentialGroup()
                .addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .add(jPanel3Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(txtPatente, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 28, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .add(jLabel5)
                    .add(btnPatente)
                    .add(jLabel2)
                    .add(txtId, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                .add(jPanel3Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(jPanel3Layout.createSequentialGroup()
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(jPanel3Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                            .add(jLabel3)
                            .add(cmbMarca, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 27, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(jPanel3Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                            .add(jLabel4)
                            .add(cmbModelo, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 27, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)))
                    .add(jPanel3Layout.createSequentialGroup()
                        .add(19, 19, 19)
                        .add(lblEstado, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 38, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)))
                .add(18, 18, 18)
                .add(jSeparator1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 10, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(jPanel3Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(btnRut)
                    .add(txtRut, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .add(jLabel1))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED)
                .add(jPanel3Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(txtNombres, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .add(jLabel6))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED)
                .add(jPanel3Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(txtApellidos, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .add(jLabel8))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED)
                .add(jPanel3Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(txtFono, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .add(jLabel9))
                .addContainerGap())
        );

        tblRegistros.setFont(new java.awt.Font("Lucida Grande", 0, 14));
        tblRegistros.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        tblRegistros.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                tblRegistrosMouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(tblRegistros);

        org.jdesktop.layout.GroupLayout jPanel5Layout = new org.jdesktop.layout.GroupLayout(jPanel5);
        jPanel5.setLayout(jPanel5Layout);
        jPanel5Layout.setHorizontalGroup(
            jPanel5Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jPanel5Layout.createSequentialGroup()
                .addContainerGap()
                .add(jScrollPane1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 505, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        jPanel5Layout.setVerticalGroup(
            jPanel5Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jPanel5Layout.createSequentialGroup()
                .addContainerGap()
                .add(jScrollPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 155, Short.MAX_VALUE)
                .addContainerGap())
        );

        btnGrabar.setText("Grabar");
        btnGrabar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnGrabarActionPerformed(evt);
            }
        });

        btnBorrar.setText("Borrar");
        btnBorrar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnBorrarActionPerformed(evt);
            }
        });

        btnSalir.setText("Salir");
        btnSalir.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSalirActionPerformed(evt);
            }
        });

        btnNuevo.setText("Nuevo");
        btnNuevo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnNuevoActionPerformed(evt);
            }
        });

        org.jdesktop.layout.GroupLayout jPanel4Layout = new org.jdesktop.layout.GroupLayout(jPanel4);
        jPanel4.setLayout(jPanel4Layout);
        jPanel4Layout.setHorizontalGroup(
            jPanel4Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(org.jdesktop.layout.GroupLayout.TRAILING, jPanel4Layout.createSequentialGroup()
                .addContainerGap(101, Short.MAX_VALUE)
                .add(btnBorrar)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED)
                .add(btnNuevo)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED)
                .add(btnGrabar)
                .add(35, 35, 35)
                .add(btnSalir)
                .add(63, 63, 63))
        );
        jPanel4Layout.setVerticalGroup(
            jPanel4Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jPanel4Layout.createSequentialGroup()
                .add(jPanel4Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(btnSalir)
                    .add(btnBorrar)
                    .add(btnNuevo)
                    .add(btnGrabar))
                .addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        txtComentarios.setColumns(20);
        txtComentarios.setRows(5);
        jScrollPane2.setViewportView(txtComentarios);

        jLabel10.setText("Tarea");

        org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(layout.createSequentialGroup()
                        .addContainerGap()
                        .add(jPanel3, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 519, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                    .add(layout.createSequentialGroup()
                        .addContainerGap()
                        .add(jPanel5, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                    .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING, false)
                        .add(org.jdesktop.layout.GroupLayout.LEADING, layout.createSequentialGroup()
                            .addContainerGap()
                            .add(jPanel4, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                        .add(org.jdesktop.layout.GroupLayout.LEADING, layout.createSequentialGroup()
                            .add(60, 60, 60)
                            .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                                .add(jSeparator2, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 479, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                                .add(layout.createSequentialGroup()
                                    .add(jLabel10)
                                    .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                                    .add(jScrollPane2, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 415, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)))
                            .add(5, 5, 5))))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .add(jPanel3, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 309, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(jSeparator2, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 12, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(jLabel10)
                    .add(jScrollPane2, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 61, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(jPanel4, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 37, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(jPanel5, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnBorrarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnBorrarActionPerformed
        // TODO add your handling code here:
}//GEN-LAST:event_btnBorrarActionPerformed

    private void btnGrabarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnGrabarActionPerformed
        // TODO add your handling code here:

        String msgerror=null;
        boolean datosOk=true;

        String patente = txtPatente.getText();
        String rut = txtRut.getText();
        String marca=Integer.toString( cmbMarca.getSelectedIndex());
        String modelo=String.valueOf( cmbModelo.getSelectedItem());

        if (patente.equals("")) {
            datosOk = false;
            msgerror = "Error: Ingrese PATENTE del vehiculo";
        }
        if (rut.equals("") && datosOk) {
            datosOk = false;
            msgerror = "Error: Ingrese RUT del cliente";
        }
        if (marca.equals("0") && datosOk) {
            datosOk = false;
            msgerror = "Error:Indique MARCA del vehiculo";
        }
        if (modelo.equals("0") && datosOk) {
            datosOk = false;
            msgerror = "Error:Indique MODELO del vehiculo";
        }

       System.out.print(marca +" "+modelo+"<....marca y modelo");
      

        if(datosOk){

            grabaformulario();

        }else{
            lblEstado.setText(msgerror);
        }

}//GEN-LAST:event_btnGrabarActionPerformed

    private void btnSalirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSalirActionPerformed
        this.dispose();
}//GEN-LAST:event_btnSalirActionPerformed

    private void tblRegistrosMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tblRegistrosMouseClicked

        String marca = null;
        String modelo = null;

        conn = new Conexion();
        cmd = new Query(conn);

        String[] campo = {"t1.id_fichaAuto", "t1.patente", "t1.comentarios", "t1.rut_cliente", "t3.nombres", "t3.apellidos", "t3.fono", "t4.nombre", "t5.nombre"};

        tbls = "tbl_fichaAuto t1, tbl_auto t2, tbl_cliente t3, tbl_modelo t4, tbl_marca t5";


        // return result[0][0].toString() + " ::: " + result[0][1].toString();

        fila = tblRegistros.rowAtPoint(evt.getPoint());
        if (fila > -1) {
            txtId.setText(String.valueOf(datos.getValueAt(fila, 0)));

            condiciones = nomkey + "=" + "'" + datos.getValueAt(fila, 0) + "'"
                    + " AND t1.patente=t2.patente "
                    + " AND t1.rut_cliente=t3.rut_cliente "
                    + " AND t2.id_modelo=t4.id_modelo "
                    + " AND t4.id_marca=t5.id_marca ";

            result = cmd.leeRegistros(campo, condiciones, tbls);

            txtPatente.setText(result[0][1].toString());
            txtComentarios.setText(result[0][2].toString());
            txtRut.setText(result[0][3].toString());
            txtNombres.setText(result[0][4].toString());
            txtApellidos.setText(result[0][5].toString());
            txtFono.setText(result[0][6].toString());
            modelo = result[0][7].toString();
            marca = result[0][8].toString();

        }

        for (int i = 0; i < cmbMarca.getItemCount(); i++) {

            System.out.println(marca + " <-> " + cmbMarca.getItemAt(i).toString());
            if (marca.equals(cmbMarca.getItemAt(i).toString())) {
                cmbMarca.setSelectedIndex(i);
                break;
            }


        }




        for (int i = 0; i < cmbModelo.getItemCount(); i++) {
            //   System.out.println(idtipo + " <-> " + cmbModelo.getItemAt(i).toString());
            if (modelo.equals(cmbModelo.getItemAt(i).toString())) {
                cmbModelo.setSelectedIndex(i);
                break;
            }


        }



        btnNuevo.setEnabled(true);
        btnBorrar.setEnabled(true);

        conn.desconectar();
    }//GEN-LAST:event_tblRegistrosMouseClicked
    private void limpiar() {
        txtId.setText("");
        txtPatente.setText("");
        txtComentarios.setText("");

        txtRut.setText("");
        txtNombres.setText("");
        txtApellidos.setText("");
        txtFono.setText("");
        lblEstado.setText("");
        cmbMarca.setSelectedIndex(0);
        cmbModelo.removeAllItems();
        btnNuevo.setEnabled(true);
        btnBorrar.setEnabled(false);

      
        llenaTabla();
    }

    private void llenaTabla() {


        conn = new Conexion();
        cmd = new Query(conn);

        condiciones = " t1.patente=t2.patente and  t1.rut_cliente=t3.rut_cliente";
        String[] columna = {"t1.id_fichaAuto", "t2.patente", "t3.rut_cliente", "t3.nombres", "t3.apellidos", "t1.comentarios"};
        String tabla = tablamaster + " t1, tbl_auto t2, tbl_cliente t3";

        result = cmd.leeRegistros(columna, condiciones, tabla);
        datos = new DefaultTableModel(result, titcols);
        tblRegistros.setModel(datos);
        conn.desconectar();
    }

    private void combomarcas() {

        conn = new Conexion();
        cmd = new Query(conn);

        cmbMarca.removeAllItems();

        String[] columnas = {"id_marca", "nombre"};
        condiciones = " 1 ORDER BY nombre asc";
        tbls = "tbl_marca";

        result = cmd.leeRegistros(columnas, condiciones, tbls);
        cmbMarca.addItem(new EntradaCombo("0", "Seleccione"));
        for (int i = 1; i < result.length; i++) {

            cmbMarca.addItem(new EntradaCombo(result[i][0].toString(), result[i][1].toString()));

        }

        conn.desconectar();
    }

    private void combomodelo(String idmarca) {

        conn = new Conexion();
        cmd = new Query(conn);

        cmbModelo.removeAllItems();

        String[] columnas = {"id_modelo", "nombre"};
        condiciones = "id_marca='" + idmarca + "'" + "  ORDER BY nombre asc";
        tbls = "tbl_modelo";

        result = cmd.leeRegistros(columnas, condiciones, tbls);
        for (int i = 0; i < result.length; i++) {

            cmbModelo.addItem(new EntradaCombo(result[i][0].toString(), result[i][1].toString()));

        }

        conn.desconectar();
    }
    
    private void getDatosCliente(String rut, Conexion conn, Query cmd) {
 

            String[] columna2 = {"rut_cliente"};
            condiciones = "rut_cliente='" + rut + "'";
            if (!cmd.existeCampo(columna2, condiciones, "tbl_cliente")) {
                lblEstado.setText("rut encontrado. Nuevo cliente");

            } else {

                System.out.println("cliente encontrado");

                String[] campos2 = {"t1.nombres", "t1.apellidos", "t1.fono"};
                result = cmd.leeRegistros(campos2, condiciones, "tbl_cliente t1");
                txtRut.setText(rut);
                txtNombres.setText(result[0][0].toString());
                txtApellidos.setText(result[0][1].toString());
                txtFono.setText(result[0][2].toString());
            }
    }

    private void getDatosPatente(Conexion conn, Query cmd) {
   


          
            condiciones = "t1.patente='" + txtPatente.getText() + "'";
            condiciones += "AND   t1.id_modelo=t2.id_modelo ";
            condiciones += "AND  t2.id_marca=t3.id_marca";
            String[] campos = {"t1.patente", "t1.id_modelo", "t1.rut_cliente", "t2.nombre", "t3.nombre", "t3.id_marca"};
            result = cmd.leeRegistros(campos, condiciones, "tbl_auto t1, tbl_modelo t2, tbl_marca t3");

            txtPatente.setText(result[0][0].toString());
            String modelo = result[0][3].toString();
            String marca = result[0][4].toString();
            String idmarca = result[0][5].toString();
            String rut = result[0][2].toString();

            for (int i = 0; i < cmbMarca.getItemCount(); i++) {

                System.out.println(marca + " <-> " + cmbMarca.getItemAt(i).toString());
                if (marca.equals(cmbMarca.getItemAt(i).toString())) {
                    cmbMarca.setSelectedIndex(i);
                    combomodelo(idmarca);
                    break;
                }


            }

            for (int i = 0; i < cmbModelo.getItemCount(); i++) {

                System.out.println("compara modelo: " + modelo + " <-> " + cmbModelo.getItemAt(i).toString());
                if (modelo.equals(cmbModelo.getItemAt(i).toString())) {
                    cmbModelo.setSelectedIndex(i);
                    break;
                }


            }
            conn.desconectar();



            /*
            consulta cliente
             */

            conn = new Conexion();
            cmd = new Query(conn);
            String[] columna2 = {"rut_cliente"};
            condiciones = "rut_cliente='" + rut + "'";
            if (!cmd.existeCampo(columna2, condiciones, "tbl_cliente")) {
                lblEstado.setText("rut encontrado. Nuevo cliente");

            } else {

                System.out.println("cliente encontrado");

                String[] campos2 = {"t1.nombres", "t1.apellidos", "t1.fono"};
                result = cmd.leeRegistros(campos2, condiciones, "tbl_cliente t1");
                txtRut.setText(rut);
                txtNombres.setText(result[0][0].toString());
                txtApellidos.setText(result[0][1].toString());
                txtFono.setText(result[0][2].toString());
            }
         




     



    }


    private void chkRut(){
         conn = new Conexion();
        cmd = new Query(conn);

        String[] columna = {"rut_cliente"};
        condiciones = "rut_cliente='" + txtRut.getText() + "'";
        if (!cmd.existeCampo(columna, condiciones, "tbl_cliente")) {
             

             lblEstado.setText("Rut no encontrado. Nuevo Cliente.");
             lblEstado.setBackground(Color.RED);
        }else{
            lblEstado.setText("Cliente existente");
             String rut = txtRut.getText();
            getDatosCliente( rut, conn, cmd);
        }
    }

    private void  chkPatente(){
         conn = new Conexion();
        cmd = new Query(conn);

        String[] columna = {"patente"};
        condiciones = "patente='" + txtPatente.getText() + "'";
        if (!cmd.existeCampo(columna, condiciones, "tbl_auto")) {
            System.out.println("no encontrado");
            lblEstado.setBackground(Color.red);
            lblEstado.setText("Patente no encontrada. Nuevo Auto.");
        } else {

              System.out.println("auto encontrado");
            lblEstado.setText("Auto existente.");
            getDatosPatente(conn,cmd);
        }
        conn.desconectar();

    }

    private void btnNuevoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnNuevoActionPerformed
        // TODO add your handling code here:
        limpiar();
}//GEN-LAST:event_btnNuevoActionPerformed

    private void cmbMarcaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmbMarcaActionPerformed

        EntradaCombo item = (EntradaCombo) cmbMarca.getSelectedItem();

        try {
            String idsel = item.getValue();
            System.out.println("ID marca:" + idsel);
            if (idsel != "0") {
                combomodelo(idsel);
            }
        } catch (Exception e) {
            System.out.println("error combo marca: " + cmbMarca.getSelectedItem());
        }
    }//GEN-LAST:event_cmbMarcaActionPerformed

    private void btnPatenteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnPatenteActionPerformed
        // TODO add your handling code here:
       chkPatente();

    }//GEN-LAST:event_btnPatenteActionPerformed

    private void btnRutActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnRutActionPerformed
       chkRut();
    }//GEN-LAST:event_btnRutActionPerformed

    private void txtIdActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtIdActionPerformed
        // TODO add your handling code here:
}//GEN-LAST:event_txtIdActionPerformed

    private void txtRutActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtRutActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_txtRutActionPerformed

    private void cmbModeloActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmbModeloActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_cmbModeloActionPerformed

    private void cmbMarcaItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_cmbMarcaItemStateChanged
        // TODO add your handling code here:
        System.out.println("----->");
    }//GEN-LAST:event_cmbMarcaItemStateChanged

    private void btnPatenteKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_btnPatenteKeyPressed

    }//GEN-LAST:event_btnPatenteKeyPressed

    private void txtRutFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_txtRutFocusLost
     chkRut();
    }//GEN-LAST:event_txtRutFocusLost

    private void txtPatenteFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_txtPatenteFocusLost
        chkPatente();
    }//GEN-LAST:event_txtPatenteFocusLost

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnBorrar;
    private javax.swing.JButton btnGrabar;
    private javax.swing.JButton btnNuevo;
    private javax.swing.JButton btnPatente;
    private javax.swing.JButton btnRut;
    private javax.swing.JButton btnSalir;
    private javax.swing.JComboBox cmbMarca;
    private javax.swing.JComboBox cmbModelo;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel10;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JLabel jLabel9;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JPanel jPanel4;
    private javax.swing.JPanel jPanel5;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JSeparator jSeparator2;
    private javax.swing.JLabel lblEstado;
    private javax.swing.JTable tblRegistros;
    private javax.swing.JTextField txtApellidos;
    private javax.swing.JTextArea txtComentarios;
    private javax.swing.JTextField txtFono;
    private javax.swing.JTextField txtId;
    private javax.swing.JTextField txtNombres;
    private javax.swing.JTextField txtPatente;
    private javax.swing.JTextField txtRut;
    // End of variables declaration//GEN-END:variables
}
